package com.coolwen.listener;

import com.coolwen.encryption.Des;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Nieyu on 2016/11/20.
 */
public class AutoBackUpListener implements ServletContextListener {

    private Timer timer;

    private String rUser;

    private String rPassword;

    private String rDbName;

    public void getDataBaseInfo() {

        Des des = new Des();
        InputStream inputStream = AutoBackUpListener.class.getResourceAsStream("/config.properties");
        Properties p = new Properties();
        try {
            p.load(inputStream);
            des.getKey(Des.generateKeyStr); // 生成密匙 （同一个key）
            rUser = des.getDesString(p.getProperty("jdbc.username"));
            rPassword = des.getDesString(p.getProperty("jdbc.password"));
            rDbName = p.getProperty("jdbc.url").substring(p.getProperty("jdbc.url").indexOf("6") +
                    2, p.getProperty("jdbc.url").indexOf("?"));
            inputStream.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    public void contextDestroyed(ServletContextEvent arg0) {
        System.out.println("shut down task.");
        timer.cancel(); //Terminate the timer thread

    }

    public void contextInitialized(ServletContextEvent arg0) {
        timer = new Timer();
        System.out.println("begin task.");

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 17);//   17：00 am 备份数据库
        calendar.set(Calendar.MINUTE, 10);
        calendar.set(Calendar.SECOND, 0);
        Date time = calendar.getTime();
        timer = new Timer();
        //timer.schedule(new RemindTask(), time);
        timer.scheduleAtFixedRate(new Beifen(), time, 1000 * 60 * 60 * 24);//每天执行一次

    }

    class Beifen extends TimerTask {

        private String user_name;//数据库用户名
        private String user_psw;//数据库密码
        private String db_name;// 需要备份的数据库名
        private String host_ip;
        private String user_charset;
        private String backup_path; //存放备份文件的路径
        private String stmt;

        public Beifen() {
        }

        public Beifen(String user_name, String user_psw, String db_name, String host_ip, String user_charset, String backup_path) {
            this.user_name = user_name;
            this.user_psw = user_psw;
            this.db_name = db_name;
            //主机IP;
            if (host_ip == null || host_ip.equals(""))
                this.host_ip = "172.16.10.80";//默认为本机
            else
                this.host_ip = host_ip;
            //字符集
            if (user_charset == null || user_charset.equals(""))
                this.user_charset = " "; //默认为安装时设置的字符集
            else
                this.user_charset = " --default-character-set=" + user_charset;
            this.backup_path = backup_path;

            /*this.stmt="C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\mysqldump "+this.db_name+" -h "+this.host_ip+" -u"+this.user_name+" -p"+this.user_psw
                    +this.user_charset+" --result-file="+this.backup_path; */
            this.stmt = "C:\\Program Files\\mysql-5.6.24-win32\\bin\\mysqldump " + this.db_name + " -h " + this.host_ip + " -u" + this.user_name + " -p" + this.user_psw
                    + this.user_charset + " --result-file=" + this.backup_path;
        }

        public boolean backup_run() {
            boolean run_result = false;
            try {
                Runtime.getRuntime().exec(this.stmt);
                run_result = true;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                return run_result;
            }
        }

        @Override
        public void run() {
            getDataBaseInfo();
            SimpleDateFormat dt = new SimpleDateFormat("yyyyMMdd");
            String date = dt.format(new Date());//获取当前时间
            Beifen backup = null;
            try {
                System.out.println(rUser);
                System.out.println(rPassword);
                System.out.println(rDbName);
                backup = new Beifen(rUser, rPassword, rDbName, null, "utf8", "d:\\" + new String(date.getBytes("GB2312"), "8859_1") + ".sql");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            boolean result = backup.backup_run();
            if (result)
                System.out.println("备份成功");
        }

    }
}
